package cn.dyw.cloudmusic.http;

import cn.dyw.cloudmusic.config.MybatisConfig;
import cn.dyw.cloudmusic.dao.CommentMapper;
import cn.dyw.cloudmusic.dao.UserMapper;
import cn.dyw.cloudmusic.http.model.Params;
import cn.dyw.cloudmusic.music.vo.Comment;
import cn.dyw.cloudmusic.music.vo.MusicComment;
import cn.dyw.cloudmusic.music.vo.User;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.log4j.Log4j;
import okhttp3.Response;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: dyw770
 * @Date: 2019/1/6 15:32
 * @Description: TODO
 */
@Data
@Log4j
public class CommentSaveHandle implements SaveHandle {

    @Override
    public void save(Response response, Params p) {
        try {
            MusicComment musicComment = JSON.parseObject(response.body().string(), MusicComment.class);
            SqlSession session = MybatisConfig.getSession();
            CommentMapper mapper = session.getMapper(CommentMapper.class);
            List<Comment> comments = musicComment.getComments();
            log.debug("获取到[" + comments.size() + "]条评论");
            List<User> users = comments.stream().map(Comment::getUser).collect(Collectors.toList());
            UserMapper userMapper = session.getMapper(UserMapper.class);
            int k = userMapper.insertList(users);
            log.debug("获取到[" + k + "]个用户");
            int i = mapper.insertList(comments, p.songId());
            session.commit();
            session.close();
            log.debug("保存[" + i + "]条评论数据");
            Thread.sleep(10 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
